<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/3 0003
 * Time: 下午 9:37
 */

namespace api\lib;


use common\config\AppConf;
use Yii;

class BaseHelper
{
    /**
     * 设置缓存，十分钟有效
     * @param $key
     * @param $data
     * @param $time
     * @return array
     */
    public static function setDataCache($key, $data, $time = 0)
    {
        $r = Yii::$app->cache->set($key, $data, $time);
        return $r ? self::renderSuccess() : self::renderError();
    }


    /**
     * 获取缓存数据
     * @param string $key
     * @return array
     */
    public static function getDataCache($key)
    {
        $data = Yii::$app->cache->get($key);
        return self::renderArray($data);
    }


    /**
     * 返回数据
     * @param $data
     * @param int $no
     * @param string $msg
     * @param bool $r
     * @return array
     */
    public static function renderArray($data, $no = AppConf::APP_NO_OK, $msg = AppConf::APP_MSG_OK, $r = true)
    {
        return ['r' => $r, 'no' => $no, 'data' => $data, 'msg' => $msg];
    }

    public static function renderError($msg = '服务器内部错误', $no = AppConf::APP_NO_DB)
    {
        return self::renderArray([], $no, $msg, false);
    }

    public static function renderSuccess()
    {
        return self::renderArray([]);
    }


    /**
     * @desc arraySort php二维数组排序 按照指定的key 对数组进行排序
     * @param array $arr 将要排序的数组
     * @param string $keys 指定排序的key
     * @param string $type 排序类型 asc | desc
     * @return array
     */
    public static function arraySort($arr, $keys, $type = 'asc') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v){
            $keysvalue[$k] = $v[$keys];
        }
        $type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }
}